<template>
  <div class="share-management">
    <div class="page-header">
      <h2>我的分享</h2>
      <p>管理您创建的所有文件分享</p>
    </div>

    <el-table :data="shares" style="width: 100%" v-loading="loading">
      <el-table-column prop="filename" label="文件名" min-width="200">
        <template #default="{ row }">
          <div class="file-info">
            <span class="file-icon">{{ getFileIcon(row.type) }}</span>
            <span class="filename">{{ row.filename }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="share_code" label="分享码" width="120">
        <template #default="{ row }">
          <el-tag type="info">{{ row.share_code }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="访问控制" width="150">
        <template #default="{ row }">
          <div class="access-control">
            <el-tag v-if="row.share_password" type="warning" size="small">
              <el-icon><Lock /></el-icon>
              有密码
            </el-tag>
            <el-tag v-else type="success" size="small">
              <el-icon><Unlock /></el-icon>
              无密码
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="有效期" width="150">
        <template #default="{ row }">
          <span v-if="row.expire_time">
            {{ formatDate(row.expire_time) }}
          </span>
          <el-tag v-else type="success" size="small">永久有效</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="访问统计" width="120">
        <template #default="{ row }">
          <div class="access-stats">
            <span>{{ row.access_count }}</span>
            <span v-if="row.max_access_count">/ {{ row.max_access_count }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="copyShareLink(row)">
            复制链接
          </el-button>
          <el-button type="info" size="small" @click="showDetails(row)">
            详情
          </el-button>
          <el-button type="danger" size="small" @click="cancelShare(row)">
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分享详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="分享详情"
      width="500px"
    >
      <div v-if="selectedShare" class="share-details">
        <div class="detail-item">
          <label>文件名：</label>
          <span>{{ selectedShare.filename }}</span>
        </div>

        <div class="detail-item">
          <label>分享链接：</label>
          <div class="link-container">
            <el-input v-model="shareLink" readonly />
            <el-button type="primary" @click="copyShareLink(selectedShare)">
              复制
            </el-button>
          </div>
        </div>

        <div class="detail-item" v-if="selectedShare.share_password">
          <label>访问密码：</label>
          <span class="password">{{ selectedShare.share_password }}</span>
        </div>

        <div class="detail-item">
          <label>分享码：</label>
          <span class="share-code">{{ selectedShare.share_code }}</span>
        </div>

        <div class="detail-item">
          <label>创建时间：</label>
          <span>{{ formatDate(selectedShare.created_at) }}</span>
        </div>

        <div class="detail-item" v-if="selectedShare.expire_time">
          <label>有效期至：</label>
          <span>{{ formatDate(selectedShare.expire_time) }}</span>
        </div>

        <div class="detail-item">
          <label>访问次数：</label>
          <span>{{ selectedShare.access_count }}</span>
          <span v-if="selectedShare.max_access_count">
            / {{ selectedShare.max_access_count }}
          </span>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getMySharesApi, cancelShareApi } from "../utils/api";
import { Lock, Unlock } from '@element-plus/icons-vue';

const shares = ref([]);
const loading = ref(false);
const detailDialogVisible = ref(false);
const selectedShare = ref(null);

const shareLink = computed(() => {
  if (!selectedShare.value) return '';
  const baseUrl = window.location.origin;
  return `${baseUrl}/#/share/${selectedShare.value.share_code}`;
});

onMounted(() => {
  loadShares();
});

const loadShares = async () => {
  loading.value = true;
  try {
    const response = await getMySharesApi();
    if (response.code === 200) {
      shares.value = response.data;
    } else {
      ElMessage.error('加载分享列表失败');
    }
  } catch (error) {
    console.error('加载分享列表失败:', error);
    ElMessage.error('加载失败，请重试');
  } finally {
    loading.value = false;
  }
};

const copyShareLink = async (share) => {
  const link = `${window.location.origin}/#/share/${share.share_code}`;
  try {
    await navigator.clipboard.writeText(link);
    ElMessage.success('分享链接已复制到剪贴板');
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea');
    textArea.value = link;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    ElMessage.success('分享链接已复制到剪贴板');
  }
};

const showDetails = (share) => {
  selectedShare.value = share;
  detailDialogVisible.value = true;
};

const cancelShare = async (share) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消分享文件 "${share.filename}" 吗？`,
      '确认取消分享',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response = await cancelShareApi({ shareId: share.id });
    if (response.code === 200) {
      ElMessage.success('取消分享成功');
      loadShares(); // 重新加载列表
    } else {
      ElMessage.error(response.msg || '取消分享失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消分享失败:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
};

const getFileIcon = (type) => {
  if (!type) return '📄';

  if (type.includes('image')) return '🖼️';
  if (type.includes('video')) return '🎬';
  if (type.includes('audio')) return '🎵';
  if (type.includes('pdf')) return '📕';
  if (type.includes('word') || type.includes('doc')) return '📘';
  if (type.includes('excel') || type.includes('sheet')) return '📗';
  if (type.includes('powerpoint') || type.includes('presentation')) return '📙';
  if (type.includes('zip') || type.includes('rar')) return '📦';
  if (type.includes('text')) return '📝';

  return '📄';
};

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN');
};
</script>

<style lang="less" scoped>
.share-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;

  h2 {
    margin: 0 0 8px 0;
    color: #303133;
  }

  p {
    margin: 0;
    color: #606266;
  }
}

.file-info {
  display: flex;
  align-items: center;

  .file-icon {
    margin-right: 8px;
    font-size: 16px;
  }

  .filename {
    word-break: break-all;
  }
}

.access-control {
  .el-tag {
    .el-icon {
      margin-right: 4px;
    }
  }
}

.access-stats {
  font-family: monospace;
  color: #606266;
}

.share-details {
  .detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    label {
      width: 80px;
      font-weight: 500;
      color: #303133;
    }

    .link-container {
      display: flex;
      flex: 1;
      gap: 10px;
    }

    .password {
      font-family: monospace;
      background: #f5f7fa;
      padding: 4px 8px;
      border-radius: 4px;
    }

    .share-code {
      font-family: monospace;
      font-weight: bold;
      color: #409eff;
    }
  }
}

@media (max-width: 768px) {
  .share-management {
    padding: 10px;
  }

  .el-table {
    font-size: 12px;
  }
}
</style>
